package com.example.dragon.xmf;

import android.content.Intent;
import android.content.SharedPreferences;
import android.support.annotation.IdRes;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.model.LatLng;
import com.example.dragon.adpter.ProblemAdpter;
import com.example.dragon.bean.ProblemBean;
import com.example.dragon.common.Common;
import com.example.dragon.fragment.OrderFragment;
import com.example.dragon.fragment.OrdersFragment;
import com.example.dragon.fragment.UserFragment;
import com.example.dragon.untis.FragmentCheck;
import com.example.dragon.untis.Utils;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.List;

import okhttp3.Call;

public class MainActivity extends AppCompatActivity implements RadioGroup.OnCheckedChangeListener {

    public AMapLocationClient mLocationClient = null;
    public AMapLocationClientOption mLocationOption = null;
    public static double getLongitude,getLatitude;
    private SharedPreferences sp;
    private RadioButton rb_secend;
    public static String TOKEN,TEL,NAME,CITY;
    RadioGroup rGroup;
    OrderFragment orderFragment;
    UserFragment userFragment;
    OrdersFragment ordersFragment;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        rb_secend = (RadioButton)findViewById(R.id.rb_second);
        sp = this.getSharedPreferences("userInfo", 0);
        TOKEN = sp.getString("token",null);
        TEL = sp.getString("mobile", null);
        NAME = sp.getString("name", null);
        Toast.makeText(getApplicationContext(),TOKEN,Toast.LENGTH_SHORT).show();
        //通过点击不同的RadioButton进行切换
        rGroup = (RadioGroup)findViewById(R.id.RGMenu);
        rGroup.setOnCheckedChangeListener(this);
        initFragment();
        initLocation();
        getFilePath();
    }
    private void initFragment() {
        if (orderFragment == null) {
            orderFragment = new OrderFragment();
        }
        if (ordersFragment == null) {
            ordersFragment = new OrdersFragment();
        }
        if (userFragment == null) {
            userFragment = new UserFragment();
        }

        showContentFragment(orderFragment, R.id.fragment_container);
    }
    
    private void initLocation(){
        mLocationOption = new AMapLocationClientOption();
        mLocationClient = new AMapLocationClient(getApplicationContext());
        mLocationClient.setLocationListener(mLocationListener);
        mLocationOption = new AMapLocationClientOption();
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
       // mLocationOption.setInterval(1000);
        mLocationOption.setNeedAddress(true);
        mLocationOption.setWifiActiveScan(false);
        mLocationOption.setHttpTimeOut(20000);
        mLocationOption.setLocationCacheEnable(false);
        mLocationClient.setLocationOption(mLocationOption);
        //启动定位
        mLocationClient.startLocation();
    }
    //声明定位回调监听器
    public AMapLocationListener mLocationListener = new AMapLocationListener() {
        @Override
        public void onLocationChanged(AMapLocation aMapLocation) {
            if (aMapLocation != null) {
                if (aMapLocation.getErrorCode() == 0) {
                    getLongitude = aMapLocation.getLongitude();
                    getLatitude = aMapLocation.getLatitude();
                    CITY = aMapLocation.getCity();
                }else {
                    //定位失败时，可通过ErrCode（错误码）信息来确定失败的原因，errInfo是错误信息，详见错误码表。
                    Log.e("AmapError","location Error, ErrCode:"
                            + aMapLocation.getErrorCode() + ", errInfo:"
                            + aMapLocation.getErrorInfo());
                }
            }
        }
    };
    protected void showContentFragment(Fragment to, int container) {
        if (to != null) {
            FragmentTransaction t = getSupportFragmentManager().beginTransaction();
            if (to.isAdded()) {
                t.show(to);
            } else {
                t.add(container, to, to.getClass().getSimpleName());
            }
            List<Fragment> fragments = getSupportFragmentManager().getFragments();
            if (fragments == null) {
                t.commit();
                return;
            }
            for (Fragment fragment : fragments) {
                if (fragment != to && !fragment.isHidden()) {
                    t.hide(fragment);
                }
            }
            t.commitAllowingStateLoss();
        }
    }
    @Override
    protected void onRestart() {
        super.onRestart();
        Intent intent = getIntent();
        if ("1".equals(intent.getStringExtra("order"))){
            rb_secend.setChecked(true);
            FragmentManager fManager = getSupportFragmentManager();
            FragmentTransaction fTransaction = fManager.beginTransaction();
            Fragment fragment = FragmentCheck.getFragmentById(R.id.rb_second);
            fTransaction.add(R.id.fragment_container, fragment);
            fTransaction.commit();
        }

    }

    @Override
    protected void onResume() {
        super.onResume();
        Intent intent = getIntent();
        if ("1".equals(intent.getStringExtra("order"))){
            FragmentManager fManager = getSupportFragmentManager();
            FragmentTransaction fTransaction = fManager.beginTransaction();
            Fragment fragment = FragmentCheck.getFragmentById(R.id.rb_second);
            rb_secend.setChecked(true);
            fTransaction.add(R.id.fragment_container, fragment);
            fTransaction.commit();
        }
    }

    private void getFilePath(){
        OkHttpUtils.post()
                .url(Common.MIFENG_URL+"Public&a=getFilePath")
                .build()//
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Log.i("res",e.toString());
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        Log.i("res",response.toString());
                        try {
                            JSONObject jsonObject =new JSONObject(response);
                            int code = jsonObject.getInt("code");
                            if (code==200){
                                Log.d("gg",jsonObject.getString("datas"));
                                sp.edit().putString("filePath", jsonObject.getString("datas")).commit();
                            }else {

                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                });
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        destroyLocation();
//        stopLocation();
     }
    private void destroyLocation(){
        if (null != mLocationClient) {
            /**
             * 如果AMapLocationClient是在当前Activity实例化的，
             * 在Activity的onDestroy中一定要执行AMapLocationClient的onDestroy
             */
            mLocationClient.onDestroy();
            mLocationClient = null;
            mLocationClient = null;
        }
    }


    /**
     * 停止定位
     *
     * @since 2.8.0
     * @author hongming.wang
     *
     */
    private void stopLocation(){
        // 停止定位
        mLocationClient.stopLocation();
    }

    @Override
    public void onCheckedChanged(RadioGroup radioGroup, @IdRes int i) {

        switch (i) {
            case R.id.rb_first:
                showContentFragment(orderFragment, R.id.fragment_container);
                break;
            case R.id.rb_second:
                showContentFragment(ordersFragment, R.id.fragment_container);
                break;
            case R.id.rb_thrid:
                showContentFragment(userFragment, R.id.fragment_container);
                break;
        }
    }

}
